import type { AiEvaluationResult, ApplicationDetailForTeacher, ApplicationItemForTeacher, ApplicationTeacherPageQuery, ReviewApplicationRequest } from "@/pages/internship/application/application-teacher/apis/type"
import type { OptionItem } from "@/pages/internship/position/apis/type"
import { ElMessage } from "element-plus"
import { defineStore } from "pinia"
import { computed, reactive, ref } from "vue"
import { evaluateApplicationApi, getApplicationDetailApi, getApplicationListApi, getApplicationOptionsApi, reviewApplicationApi } from "@/pages/internship/application/application-teacher/apis"
import { usePositionTeacherStore } from "./position-teacher"
import { useUserStore } from "./user"

/**
 * 老师端职位申请状态管理
 */
export const useApplicationTeacherStore = defineStore("application-teacher", () => {
  // 响应式数据
  const loading = ref(false)
  const applicationList = ref<ApplicationItemForTeacher[]>([])
  const total = ref(0)
  const statusOptions = ref<OptionItem[]>([])
  const optionsLoading = ref(false)
  const currentApplicationDetail = ref<ApplicationDetailForTeacher | null>(null)
  const detailLoading = ref(false)
  const reviewLoading = ref(false)
  const aiEvaluation = ref<AiEvaluationResult | null>(null)
  const evaluationLoading = ref(false)
  const evaluationError = ref<string | null>(null)
  const queryParams = reactive<ApplicationTeacherPageQuery>({
    positionId: undefined,
    studentName: "",
    applicationStatus: undefined,
    page: 1,
    size: 10
  })

  /**
   * 获取申请列表
   */
  const fetchApplicationList = async () => {
    if (loading.value) return

    loading.value = true
    try {
      const response = await getApplicationListApi(queryParams)
      if (response?.data?.records) {
        applicationList.value = response.data.records || []
        total.value = response.data.total || 0
      } else {
        ElMessage.error(response?.message || "获取申请列表失败")
      }
    } catch (error) {
      console.error("获取申请列表失败:", error)
      ElMessage.error("获取申请列表失败")
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取选项数据
   */
  const fetchOptions = async () => {
    if (optionsLoading.value) return

    optionsLoading.value = true
    try {
      const response = await getApplicationOptionsApi()
      // 初始化默认空数组，确保始终是数组类型
      let optionsData: OptionItem[] = []

      if (response?.data) {
        if (response.data.applicationStatusOptions && Array.isArray(response.data.applicationStatusOptions)) {
          optionsData = response.data.applicationStatusOptions
        }
      }

      statusOptions.value = optionsData
    } catch (error) {
      console.error("获取选项数据失败:", error)
      ElMessage.error("获取选项数据失败")
      // 发生错误时确保statusOptions为空数组
      statusOptions.value = []
    } finally {
      optionsLoading.value = false
    }
  }

  /**
   * 重置查询参数
   */
  const resetQueryParams = () => {
    Object.assign(queryParams, {
      positionId: undefined,
      studentName: "",
      applicationStatus: undefined,
      page: 1,
      size: 10
    })
  }

  /**
   * 设置职位ID
   */
  const setPositionId = (positionId?: number) => {
    queryParams.positionId = positionId
    queryParams.page = 1 // 重置页码
  }

  /**
   * 获取申请详情
   */
  const fetchApplicationDetail = async (applicationId: number) => {
    if (detailLoading.value) return null

    detailLoading.value = true
    try {
      const response = await getApplicationDetailApi(applicationId)
      if (response?.data) {
        currentApplicationDetail.value = response.data
        return response.data
      } else {
        ElMessage.error(response?.message || "获取申请详情失败")
        return null
      }
    } catch (error) {
      console.error("获取申请详情失败:", error)
      ElMessage.error("获取申请详情失败")
      return null
    } finally {
      detailLoading.value = false
    }
  }

  /**
   * 审核申请
   */
  const reviewApplication = async (reviewData: ReviewApplicationRequest): Promise<boolean> => {
    if (reviewLoading.value) return false

    reviewLoading.value = true
    try {
      const userStore = useUserStore()
      const currentUserId = userStore.userInfo?.userId || 0

      // 构造符合新接口要求的数据结构
      const requestData = {
        applicationId: reviewData.applicationId,
        reviewTeacherId: currentUserId,
        applicationStatus: reviewData.applicationStatus,
        reviewRemark: reviewData.reviewRemark
      }

      const response = await reviewApplicationApi(requestData)
      console.log(response)

      if (response?.data) {
        ElMessage.success("审核成功")
        await fetchApplicationList()
        await fetchApplicationDetail(reviewData.applicationId)
        return true
      } else {
        ElMessage.error(response?.message || "审核失败")
        return false
      }
    } catch (error) {
      console.error("审核申请失败:", error)
      ElMessage.error("审核申请失败")
      return false
    } finally {
      reviewLoading.value = false
    }
  }

  /**
   * 获取AI评估结果
   */
  const fetchAiEvaluation = async (applicationId: number) => {
    if (evaluationLoading.value) return null

    evaluationLoading.value = true
    evaluationError.value = null // 重置错误状态
    try {
      const response = await evaluateApplicationApi(applicationId)
      if (response?.data) {
        aiEvaluation.value = response.data
        return response.data
      } else {
        const errorMsg = response?.message || "获取AI评估结果失败"
        ElMessage.error(errorMsg)
        evaluationError.value = errorMsg
        return null
      }
    } catch (error) {
      console.error("获取AI评估结果失败:", error)
      // 优化错误信息处理
      let errorMsg = "获取AI评估结果失败，请稍后重试"

      if (error instanceof Error) {
        // 处理常见错误类型
        if (error.message.includes("timeout") || error.message.includes("超时")) {
          errorMsg = "AI评估请求超时，请稍后重试"
        } else if (error.message.includes("Network Error")) {
          errorMsg = "网络连接异常，请检查网络后重试"
        } else {
          errorMsg = error.message
        }
      }

      ElMessage.error(errorMsg)
      evaluationError.value = errorMsg
      return null
    } finally {
      evaluationLoading.value = false
    }
  }

  /**
   * 清除当前详情和评估结果
   */
  const clearCurrentDetail = () => {
    currentApplicationDetail.value = null
    aiEvaluation.value = null
    evaluationError.value = null
  }

  // 从position-teacher store获取positionDetail
  const positionDetail = computed(() => {
    const positionTeacherStore = usePositionTeacherStore()
    return positionTeacherStore.positionDetail
  })

  return {
    // 状态
    loading,
    applicationList,
    total,
    positionDetail,
    statusOptions,
    optionsLoading,
    currentApplicationDetail,
    detailLoading,
    reviewLoading,
    evaluationLoading,
    aiEvaluation,
    evaluationError,
    queryParams,
    // 方法
    fetchApplicationList,
    fetchOptions,
    resetQueryParams,
    setPositionId,
    fetchApplicationDetail,
    fetchAiEvaluation,
    reviewApplication,
    clearCurrentDetail
  }
})
